package com.kgc.dao;

import com.kgc.entity.Repair;
import com.kgc.untils.PageUtils;
import org.apache.commons.lang3.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RepairDao extends BaseDao {

    /**
     * 查所有
     *
     * @param pageUtils
     * @param name
     * @return
     */
    public List<Repair> selectAll(PageUtils pageUtils, String name) {
        List<Repair> list = new ArrayList<>();
        try {
            String sql = "SELECT re.id,re.content,u.username,re.`status`,re.time,re.result FROM repair re left JOIN user u ON re.user_id=u.id";
            if (StringUtils.isNotEmpty(name)) {
                sql += " where re.status=" + name;
            }
            sql += " limit ?,?";
            ResultSet rs = super.getExecuteQuery(sql, pageUtils.start(), pageUtils.getPageSize());
            while (rs.next()) {
                list.add(new Repair(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getTimestamp(5), rs.getString(6)));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            super.closeConnection();
        }
        return list;

    }

    /**
     * 查总数
     *
     * @param name
     * @return
     */
    public int countAll(String name) {

        try {
            String sql = "select count(*) from repair";
            if (StringUtils.isNotEmpty(name)) {
                sql += " where `status`=" + name;
            }
            ResultSet rs = super.getExecuteQuery(sql);
            if (rs.next()) {
                return rs.getInt(1);

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            super.closeConnection();
        }
        return 0;
    }

    public int updateRepair(Repair repair) {
        String sql = "UPDATE repair SET `content` = ?,  `time` =?, `result` = ? , `status` =? where `id` = ?";
        return super.getExecuteUpdate(sql, repair.getContent(), repair.getTime(), repair.getResult(), repair.getStatus(), repair.getId());
    }

    public int deleteRepair(String id) {
        String sql = "DELETE FROM repair WHERE `id` = ?";
        return super.getExecuteUpdate(sql, id);
    }
}
